<template>
    <div>SpuForm</div>
    <el-button @click="$emit('setShowStatus', ShowStatus.SPU_LIST)">取消</el-button>

    <el-form>
        <el-form-item label="SPU名称">
            <el-input type="text" placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
            <el-select v-model="spuInfo.tmId">
                <el-option v-for="tm in trademarkList" :value="tm.id as number" :key="tm.id" :label="tm.tmName"></el-option>

            </el-select>
        </el-form-item>
        <el-form-item label="SPU描述">
            <el-input type="textarea" placeholder="SPU描述" v-model="spuInfo.description"></el-input>
        </el-form-item>


        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuInfo.spuImageList as any" list-type="picture-card"
                :action="`${BASE_UPLOAD} /admin/product / fileUpload`" :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove" :on-success="handleSuccess">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>

        <el-form-item label="SPU销售属性">
            <div>
                <el-select :placeholder="selectText">
                    <el-option :label="attr.name" :value="attr.id" v-for="attr in restSaleAttrList"
                        :key="attr.id"></el-option>

                </el-select>
                <el-button type="primary" :icon="Plus"></el-button>
            </div>

            <el-table :data="spuInfo.spuSaleAttrList" style="margin-top: 10px;">
                <el-table-column label="序号" type="index" width="80" align="center"></el-table-column>
                <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
                <el-table-column label="属性值名称列表">
                    <template v-slot="{ row, $index }">
                        <el-tag v-for="value in row.spuSaleAttrValueList" :key="value.id" closable>{{
                            value.saleAttrValueName
                        }}</el-tag>
                        <el-input v-if="row.isEdit" style="width: 100px;" @blur="toShow(row)" ref="inputRef"
                            v-model="valueName" placeholder="名称"></el-input>
                        <el-button size="small" :icon="Plus" @click="toEdit(row)"></el-button>
                    </template>

                </el-table-column>
                <el-table-column label="操作">
                    <el-button type="danger" :icon="Delete"></el-button>
                </el-table-column>
            </el-table>
        </el-form-item>


        <el-form-item>
            <el-button type="primary">保存</el-button>
            <el-button @click="$emit('setShowStatus', ShowStatus.SPU_LIST)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import type { BaseSaleAttrListModel, SpuModel, SupSaleAttrMOdel } from '@/api/product/model/spuModel';
import type { TrademarksModel } from '@/api/product/model/trademarkModel';
import { getAllTrademarkListApi, getBaseSaleAttrListApi, getSpuImageListApi, getSpuSaleAttrListApi } from '@/api/product/spu';
import { Delete, Plus } from '@element-plus/icons-vue';
import type { InputInstance, UploadProps, UploadUserFile } from 'element-plus';
import { computed, defineComponent, nextTick, onMounted, reactive, ref } from 'vue'
import { ShowStatus } from '../types';
export default defineComponent({
    name: 'SpuForm'
})
</script>
<script lang="ts" setup>
//声明接收props
const props = defineProps<{
    spu: SpuModel
}
>()

//spu销售属性处理
const inputRef = ref<InputInstance>()

const valueName = ref('')

//切换为查看模式
const toShow = (row: SupSaleAttrMOdel) => {
    //只有输入了值和不重复才会显示
    if (valueName.value) {
        //判断不重复
        const notRepeat = row.spuSaleAttrValueList.every(item => item.saleAttrValueName !== valueName.value)
        if (notRepeat) {
            //创建一个属性值对象
            const attrValu = {
                saleAttrValueName: valueName.value,
                baseSaleAttrId: row.baseSaleAttrId
            }
            //添加到属性值里
            row.spuSaleAttrValueList.push(attrValu)
        }


    }
    //变为查看模式
    row.isEdit = false
    //清除收集的输入证据
    valueName.value = ''

}
//切换为编辑模式
const toEdit = (row: SupSaleAttrMOdel) => {
    //isEdit变为true
    row.isEdit = true
    //自动获得焦点
    nextTick(() => {
        inputRef.value?.focus()
    })
}






//声明一个用于收集spu表单数据的spu详细信息对象
const spuInfo = reactive<SpuModel>(props.spu)



//声明定义自定义事件
const emit = defineEmits<
    { (e: 'setShowStatus', value: ShowStatus): void }
>()


//初始化请求

//所有品牌的列表
const trademarkList = ref<TrademarksModel>([])

//所有销售属性的列表
const saleAtteList = ref<BaseSaleAttrListModel>([])



//剩余可选的销售属性列表
const restSaleAttrList = computed(() => {
    return saleAtteList.value.filter(attr => {
        return !spuInfo.spuSaleAttrList.some
            // attr.name在spuInfo.spuSaleAttrList中有没有对应的
            (saleAttr => saleAttr.saleAttrName === attr.name)
    })
})

//计算出下拉列表的提示文本
const selectText = computed(() => {
    const length = restSaleAttrList.value.length
    return length === 0 ? '没有啦！' : `还有${length}个可选的`
})



/* 
1. 获取所有品牌列表 trademark.getAllTrademarkListApi()  trademarkList
2. 获取基础销售属性列表  spu.getBaseSaleAttrListApi()  saleAttrList
3. 获取spu图片列表   spu.getSpuImageListApi(spuId)  spuInfo.spuImageList
4. 获取spu销售属性列表  spu.getSpuSaleAttrListApi(spuId)  spuInfo.spuSaleAttrList
*/


onMounted(async () => {
    trademarkList.value = await getAllTrademarkListApi()
})
onMounted(async () => {
    saleAtteList.value = await getBaseSaleAttrListApi()
})

onMounted(async () => {
    const spuImageList = await getSpuImageListApi(spuInfo.id!)
    spuInfo.spuImageList = spuImageList.map(item => ({
        ...item,
        name: item.imgName,
        url: item.imgUrl
    }))
})
onMounted(async () => {
    const spuSaleAttrList = await getSpuSaleAttrListApi(spuInfo.id as number)
    spuInfo.spuSaleAttrList = spuSaleAttrList
})





/* 图片上传处理 start */
// const fileList = ref<UploadUserFile[]>([
//     {
//         name: 'food.jpeg',
//         url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//     },
//     {
//         name: 'food.jpeg',
//         url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//     },
// ])

const BASE_UPLOAD = import.meta.env.VITE_BASE_URL// 代理的基础路径

//大图
const dialogImageUrl = ref('')
//是否显示大图
const dialogVisible = ref(false)
//点击删除回调
//uploadFile:要删除的图片对象
//uploadFiles:剩余的图片列表
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    spuInfo.spuImageList = uploadFiles as any  // 数据等到发请求前进行整理
}
// 点击放大镜的回调
// uploadFile: 点击的图片对象
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    // 指定要显示的大图url
    dialogImageUrl.value = uploadFile.url!
    // 显示dialog
    dialogVisible.value = true
}
// 上传成功的回调
// response: 上传请求的响应体数据  {data: 图片的url}
// uploadFile: 上传成功的图片对象
// uploadFiles: 已上传的图片列表

const handleSuccess: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
    console.log('onSuccess', uploadFiles)
    spuInfo.spuImageList = uploadFiles as any  // 数据等到发请求前进行整理
}

/* 图片上传处理 end */
</script>

<style lang="less" scoped></style>